<?php

namespace Trait;

use App\Constants\ErrorCode;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

trait ResponseMsg
{
    /**成功
     * @param $data
     * @param string $msg
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function success($data = [], string $msg = ''): \Psr\Http\Message\ResponseInterface
    {
        $response = container()->get(ResponseInterface::class);
        $data = [
            'msg' => $msg ?: ErrorCode::getMessage(ErrorCode::SUCCESS),
            'code' => ErrorCode::SUCCESS,
            'success' => true,
            'data' => $data ?? []
        ];
        return $response->json($data);
    }

    /**
     * 响应错误
     * @param array $data
     * @param int $code
     * @param string $msg
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function error(mixed $code = ErrorCode::ERR, string $msg = '', array $data = []): \Psr\Http\Message\ResponseInterface
    {
        $response = container()->get(ResponseInterface::class);
        $data = [
            'msg' => $msg ?: ErrorCode::getMessage($code),
            'code' => $code,
            'success' => false,
            'data' => $data
        ];
        return $response->json($data);
    }
}
